#include "upload.h"

extern char *LOGIN_USER;
extern char *LOGIN_PASSWORD;
extern int PRIORITY_CONF;
/**
 * @description: 文件上传
 * @param {char} *pJson
 * @return {*} 低于0说明有问题
 */
int terminalLog(char *pJson)
{
    dzlog_debug("terminalLog start");
    ST_IOTA_LOG log;
    ST_IOTA_LOG_PARAM param;
    log.param = &param;
    JsonToStruct_LogUpload(pJson, &log);
    // 生成字符串结构体
    char *psJson = NULL;
    char uid[80] = {0};
    int ret = -1;
    GF_GetGUID(uid);
    ST_IOTA_LOG_RES log_res;
    ST_IOTA_LOG_BODY log_body;

    log_res.body = &log_body;
    log_res.deviceID = log.deviceID;
    log_res.deviceSn = log.deviceSn;
    log_res.iMid = uid;
    log_res.node = log.node;
    log_res.replyId = log.iMid;
    log_res.requestID = log.requestID;
    log_res.zone = log.zone;

    if (calculate_file_size(param.logPath) < 0)
    {
        log_res.code = 420;
        log_res.body = "now is download";
        dzlog_info("no file is here %s", param.logPath);
        StructToJson_LogUploadRes(&psJson, &log_res, true);
        IOTA_SendMqtt("/v1/devices/dictionary/response", psJson, strlen(psJson));
        goto Llogin;
    }

    char cmd[100] = {0};
    sprintf(cmd, "tar -cvf log.tar %s", param.logPath);
    FILE *pcmd = popen(cmd, "r");
    pclose(pcmd);

    // 开始下载
    log_res.code = 100;
    // log_res.body = "now is update file";
    dzlog_info("update file:%s", param.logPath);
    StructToJson_LogUploadRes(&psJson, &log_res, true);
    ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
    free_s(psJson);

    ST_IOTA_LOGIN_RES_V1 login = {0};
    ST_IOTA_AUTH_RES_V1 auth = {0};
    login.data = &auth;

    int ret1 = 0;
    // TODO 用户账户登录
    ret = httpFileServerLoginWithUser_v1(&login, LOGIN_USER, LOGIN_PASSWORD, "iotplatform", "password");
    if (ret < 0)
    {
        dzlog_error("login fileserver error");
        log_res.code = 500;
        log_res.body = "file service 500";
        StructToJson_LogUploadRes(&psJson, &log_res, true);
        ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        goto Llogin;
    }
    // token登录获取发送文件信息
    // ST_IOTA_AUTH_RES auth;
    // ret = httpFileServerGetHeader_v1(access_token, &auth);
    // if (ret < 0)
    // {
    //     dzlog_error("access_token error");
    //     goto Lauth;
    // }
    // 上传文件
    int ii = 0;
    ST_IOTA_FILE_RES file = {0};
    for (ii = 0; ii < 3; ii++) // 生产发现可能会超时，加三次尝试
    {
        ret = httpFileServerUploadFile_v1("log.tar", &auth, &file, NULL);
        if (ret >= 0)
        {
            break;
        }
        free_s(file.message);
        sleep(1);
    }
    if (ret < 0)
    {
        dzlog_error("file upload error");
        if (ret == -2)
        {
            log_res.code = 500;
            log_res.body = "No such file or directory (os error 2)";
            StructToJson_LogUploadRes(&psJson, &log_res, true);
            ret1 = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        }
        else if (ret == -3)
        {
            log_res.code = 500;
            log_res.body = "extract log success: no data";
            StructToJson_LogUploadRes(&psJson, &log_res, true);
            ret1 = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        }
        else if (ret == -1)
        {
            log_res.code = 500;
            log_res.body = "Timeout was reached";
            StructToJson_LogUploadRes(&psJson, &log_res, true);
            ret1 = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        }
        goto Lfile;
    }
    // 从data里面获取filedID
    ST_IOTA_FILE_DATA file_data;
    JsonToStruct_LogFileData(file.data, &file_data);
    // 上传文件
    char md5[100] = {0};
    calculate_md5("log.tar", md5);
    log_body.size = file_data.fileSize;
    log_body.md5 = md5;
    log_body.filed = file_data.fileId;
    log_body.FileName = param.logPath;
    log_res.node = file_data.node;
    log_res.zone = file_data.zone;
    char *last_slash = strrchr(param.logPath, '/');
    char result[64];
    if (last_slash)
    {
        strncpy(result, last_slash + 1, sizeof(result));
        result[sizeof(result) - 1] = '\0';
        printf("截取后的字符串： %s", result);
        log_body.FileName = "log.tar";
    }
    else
    {
        printf("未找到/字符");
    }
    // if (StructToJson_LogUploadRes(&psJson, &log_res, false))
    // {
    //     ret1 = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
    // }
    // else
    // {
    //     dzlog_error("json生成error");
    //     goto Llogin;
    // }
    // memset(psJson, 0, strlen(psJson));
    log_res.code = 200;
    StructToJson_LogUploadRes(&psJson, &log_res, false);
    ret1 = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
    // memset(psJson, 0, strlen(psJson));

    free(file_data.fileId);

Lfile:
    free_s(file.data);
    free_s(file.message);
Lauth:
    free_s(auth.nonce);
    free_s(auth.token);
    free_s(auth.timestamp);
Llogin:
    free_s(login.message);
    free_s(log.iMid);
    free_s(log.deviceSn);
    free_s(log.deviceID);
    free_s(log.msgTime);
    free_s(log.node);
    free_s(log.requestID);
    free_s(log.Servicename);
    free_s(log.zone);
    // free(log);
    free_s(param.beginTime);
    free_s(param.endTime);
    free_s(param.logPath);
    free_s(psJson);
    return ret1;
}

int file_download_v1(char *filename, ProgressInfo *info)
{
    dzlog_debug("download file %s", filename);
    char access_token[1024] = {0};
    // TODO 用户账户登录 暂时写在代码里
    int ret = httpFileServerLoginWithUser(access_token, "rsaLVBXZtwoEiOeY9eZ7SAjdWBgcgSpF6qBOZHvFtqlBHgvEdPNEUDg2ggDSW6BBy9mt1Pstp2ZilbeVIUnBsCi+jZshcJifsnhW703rHq5irWVxCdEWiSmyOlrP8Wdd/wJ3JiXX81kifo5xw9fno+zmcAlGoDSuaIRfbZi+xfd1QocI59yn/OHUgZPXyJiI4eGnyaJJ6vqQWNwcVGjgb3Nv1Y/OuzhKoocFF0R5VuYgGvOapTj7lbPQIzryQOSbwj2YtmiTl+dn6WOmAUgnhDttTJrg9P8aML7zQJdZgEBBtTlhcq5DNp/EKNrubxaXbnnU2mhrJ/J3fpPkkz6ig8iNg==", "rsaUfXm1rchfESH9Eb92tEaeor7S4Xi0jRqpQyku4clJFFLMNEsfgbGqQ/NtZmXF+XJSHXoTVABS2ucLlpJrPz2i8/2AeMcYCpVdxaJYIJS9Y7nJ+hV21E/hLAgfICls6VM+lwGq20X/M8EU2qRzwM9Ni+njbpmq9Jy6IT4vU+Ra2l5BJPjJXoZRpmC1TriAfWOQMg1SFCneH+C3DBbC31cUUhztPUia553Rv0aG0C79Wb43QA9Cn9UI41fsgacyWWprh3KAYF/kICS5lfKGAqccUMSsTSP1UZcixh3shNkMAdPHFGEuo3Jj9SUTR1n8H/CohL0UV0O/43jUMrpAVfWig==", "iotplatform", "password");

    if (ret < 0)
    {
        dzlog_error("login fileserver error");
        goto Lauth;
    }
    // token登录获取发送文件信息
    ST_IOTA_AUTH_RES auth;
    ret = httpFileServerGetHeader(access_token, &auth);
    if (ret < 0)
    {
        dzlog_error("access_token error");
        return ret;
    }

    // 暂时用固定值
    ret = httpFileServerDownload(&auth, info->fileid, filename, NULL, info);

    if (ret < 0)
    {
        dzlog_error("download1 error ");
        goto Lauth;
    }
Lauth:
    free(auth.accessKey);
    free(auth.contentType);
    free(auth.nonce);
    free(auth.sign);
    free(auth.timestamp);
    free(auth.url);

    return ret;
}

int file_download(char *filename, ProgressInfo *info)
{
    dzlog_info("file_download_v1 start file %s ,fileid:%s", filename, info->fileid);
    int ret = -1;

    ST_IOTA_LOGIN_RES_V1 login = { 0 };
    ST_IOTA_AUTH_RES_V1 auth = { 0 };
    login.data = &auth;

    // TODO 用户账户登录 暂时写在代码里
    dzlog_debug("file_download_v1 start  11 LOGIN_USER %s, LOGIN_PASSWORD:%s", LOGIN_USER, LOGIN_PASSWORD);
    //int ret = -1;
    ret = httpFileServerLoginWithUser_v1(&login, LOGIN_USER, LOGIN_PASSWORD, "iotplatform", "password");
    if (ret < 0)
    {
        int ii = 0;
        for (ii = 0; ii < 3; ii++)
        {
            sleep(3);
            ret = httpFileServerLoginWithUser_v1(&login, LOGIN_USER, LOGIN_PASSWORD, "iotplatform", "password");
            if (ret >= 0)
            {
                break;
            }
            free_s(login.message);
        }
    }
    if (ret < 0)
    {
        dzlog_error("login fileserver error");
        printf("login fileserver error\n");
        goto End;
    }
    dzlog_debug("httpFileServerLoginWithUser_v1 after token[%s] nonce[%s]", auth.token, auth.nonce);

    // 暂时用固定值
    ret = httpFileServerDownload_v1(&auth, info->fileid, filename, NULL, info);
    dzlog_info("httpFileServerDownload_v1 1 ret = %d", ret);
    long count = 0;
    while (ret < 0)
    {
        info->Bytes_bak = info->Bytes + info->Bytes_bak;
        info->Bytes = 0;
        printf("download error2\n");
        sleep(5);
        if (count++ > 60 + 3)
        {
            dzlog_error("httpFileServerDownload_v1 error time out");
            break;
        }
        ret = httpFileServerDownload_v1(&auth, info->fileid, filename, NULL, info);
        dzlog_info("httpFileServerDownload_v1 2 ret = %d", ret);
    }
Lauth:
    free_s(auth.nonce);
    free_s(auth.token);
    free_s(auth.timestamp);
    free_s(login.message);

End:
    return ret;
}

/**
 * @description: 上传对应日志等级文件
 * @param {char} *pJson
 * @return {*}
 */
int terminalLogLevel(char *pJson)
{
    ST_IOTA_LOG log;
    ST_IOTA_LOG_RULE_PARAM param;
    log.param = &param;
    JsonToStruct_LogRule(pJson, &log);

    char *psJson = NULL;
    char uid[80] = {0};
    GF_GetGUID(uid);
    ST_IOTA_LOG_RES log_res;
    log_res.body = "";
    log_res.deviceID = log.deviceID;
    log_res.deviceSn = log.deviceSn;
    log_res.iMid = uid;
    log_res.node = log.node;
    log_res.replyId = log.iMid;
    log_res.requestID = log.requestID;
    log_res.zone = log.zone;
    char file_name[100] = {0};
    // TODO暂时用分文件的日志来弄上传，只做warn和error
    if (strstr(param.regex, "error") || strstr(param.regex, "ERROR"))
    {
        char *path = strrchr(param.path, '/');
        sprintf(file_name, "%s%sERROR.log", path, FILE_LOG);
    }
    else if (strstr(param.regex, "warn") || strstr(param.regex, "WARN"))
    {
        char *path = strrchr(param.path, '/');
        sprintf(file_name, "%s%sWARN.log", path, FILE_LOG);
    }
    else if (strstr(param.regex, "debug") || strstr(param.regex, "DEBUG"))
    {
        char *path = strrchr(param.path, '/');
        sprintf(file_name, "%s%sDEBUG.log", path, FILE_LOG);
    }
    else if (strstr(param.regex, "info") || strstr(param.regex, "INFO"))
    {
        char *path = strrchr(param.path, '/');
        sprintf(file_name, "%s%sINFO.log", path, FILE_LOG);
    }

    char access_token[1024] = {0};
    // TODO 用户账户登录 暂时写在代码里
    int ret = httpFileServerLoginWithUser(access_token, "rsaLVBXZtwoEiOeY9eZ7SAjdWBgcgSpF6qBOZHvFtqlBHgvEdPNEUDg2ggDSW6BBy9mt1Pstp2ZilbeVIUnBsCi+jZshcJifsnhW703rHq5irWVxCdEWiSmyOlrP8Wdd/wJ3JiXX81kifo5xw9fno+zmcAlGoDSuaIRfbZi+xfd1QocI59yn/OHUgZPXyJiI4eGnyaJJ6vqQWNwcVGjgb3Nv1Y/OuzhKoocFF0R5VuYgGvOapTj7lbPQIzryQOSbwj2YtmiTl+dn6WOmAUgnhDttTJrg9P8aML7zQJdZgEBBtTlhcq5DNp/EKNrubxaXbnnU2mhrJ/J3fpPkkz6ig8iNg==", "rsaUfXm1rchfESH9Eb92tEaeor7S4Xi0jRqpQyku4clJFFLMNEsfgbGqQ/NtZmXF+XJSHXoTVABS2ucLlpJrPz2i8/2AeMcYCpVdxaJYIJS9Y7nJ+hV21E/hLAgfICls6VM+lwGq20X/M8EU2qRzwM9Ni+njbpmq9Jy6IT4vU+Ra2l5BJPjJXoZRpmC1TriAfWOQMg1SFCneH+C3DBbC31cUUhztPUia553Rv0aG0C79Wb43QA9Cn9UI41fsgacyWWprh3KAYF/kICS5lfKGAqccUMSsTSP1UZcixh3shNkMAdPHFGEuo3Jj9SUTR1n8H/CohL0UV0O/43jUMrpAVfWig==", "iotplatform", "password");
    if (ret < 0)
    {
        dzlog_error("login fileserver error");
        goto Llogin;
    }
    // token登录获取发送文件信息
    ST_IOTA_AUTH_RES auth;
    ret = httpFileServerGetHeader(access_token, &auth);
    if (ret < 0)
    {
        dzlog_error("access_token error");
        goto Lauth;
    }
    // 上传文件
    ST_IOTA_FILE_RES file;
    ret = httpFileServerUploadFile(file_name, &auth, &file);
    if (ret < 0)
    {
        dzlog_error("file upload error");
        if (ret == -2)
        {
            log_res.code = 500;
            log_res.body = "No such file or directory (os error 2)";
            StructToJson_LogUploadRes(&psJson, &log_res, true);
            ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        }
        else if (ret == -3)
        {
            log_res.code = 500;
            log_res.body = "extract log success: no data";
            StructToJson_LogUploadRes(&psJson, &log_res, true);
            ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        }
        goto Lfile;
    }

    // 从data里面获取filedID
    ST_IOTA_FILE_DATA file_data;
    JsonToStruct_LogFileData(file.data, &file_data);

    // 上传文件待确定
    log_res.code = 100;

    if (StructToJson_LogUploadRes(&psJson, &log_res, false))
    {
        // ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        free_s(psJson);
    }
    else
    {
        dzlog_error("json生成error");
        goto Lfile;
    }
    // memset(psJson, 0, strlen(psJson));
    // 上传文件确定
    ret = httpFileServerUploadFileReturn(file.data, access_token);
    if (ret < 0)
    {
        dzlog_error("FileServerUploadFileReturn error");
        log_res.code = 500;
        log_res.body = "load file success return error";
        StructToJson_LogUploadRes(&psJson, &log_res, true);
        ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
        goto Lfile;
    }

    log_res.code = 200;
    StructToJson_LogUploadRes(&psJson, &log_res, false);
    ret = IOTA_SendMqtt("/v1/devices/device/response", psJson, strlen(psJson));
    // memset(psJson, 0, strlen(psJson));

Lfile:
    free_s(file.data);
    free_s(file.message);
    free_s(file_data.fileId);

Lauth:
    free_s(auth.accessKey);
    free_s(auth.contentType);
    free_s(auth.nonce);
    free_s(auth.sign);
    free_s(auth.timestamp);
    free_s(auth.url);
Llogin:
    free_s(log.iMid);
    free_s(log.deviceSn);
    free_s(log.deviceID);
    free_s(log.msgTime);
    free_s(log.node);
    free_s(log.requestID);
    free_s(log.Servicename);
    free_s(log.zone);
    // free(log_res.deviceID);
    // free(log_res.deviceSn);
    // free(log_res.node);
    // free(log_res.replyId);
    // free(log_res.requestID);
    // free(log_res.zone);
    free_s(param.path);
    free_s(param.regex);
    free_s(psJson);

    return ret;
}
